const path = require('path');
const fs = require('fs');
const multer = require('multer');

// 确保上传目录存在
const ensureDir = (dirPath) => {
  try {
    fs.mkdirSync(dirPath, { recursive: true });
  } catch (_) {}
};

const UPLOAD_BASE_DIR = path.join(__dirname, '..', 'uploads');
const IMAGE_DIR = path.join(UPLOAD_BASE_DIR, 'images');
ensureDir(IMAGE_DIR);

// 允许的图片 MIME 类型
const ALLOWED_IMAGE_MIME = new Set([
  'image/png',
  'image/jpeg',
  'image/webp',
]);

// Multer 配置
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, IMAGE_DIR);
  },
  filename: function (req, file, cb) {
    const ext = path.extname(file.originalname || '').toLowerCase();
    const safeExt = ['.png', '.jpg', '.jpeg', '.webp'].includes(ext) ? ext : '.png';
    const filename = `${Date.now()}_${Math.random().toString(36).slice(2, 8)}${safeExt}`;
    cb(null, filename);
  }
});

const fileFilter = (req, file, cb) => {
  if (ALLOWED_IMAGE_MIME.has(file.mimetype)) {
    return cb(null, true);
  }
  const err = new Error('不支持的文件类型');
  err.status = 400;
  return cb(err);
};

const upload = multer({
  storage,
  fileFilter,
  limits: {
    fileSize: 5 * 1024 * 1024 // 5MB
  }
});

// 控制器：上传单张图片
const uploadImage = [
  upload.single('file'),
  async (req, res) => {
    try {
      if (!req.file) {
        return res.status(400).json({ success: false, message: '未接收到文件' });
      }

      const file = req.file;
      const url = `/uploads/images/${file.filename}`;
      const absoluteUrl = `${req.protocol}://${req.get('host')}${url}`;

      // 宽高信息（后续可用 sharp 获取像素）
      const meta = {
        url,
        absoluteUrl,
        mime: file.mimetype,
        size: file.size,
        originalName: file.originalname,
        width: null,
        height: null
      };

      return res.json({ success: true, data: meta });
    } catch (error) {
      console.error('上传图片失败:', error);
      return res.status(500).json({ success: false, message: '上传图片失败', error: error.message });
    }
  }
];

module.exports = {
  uploadImage
};


